from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info.models import User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import admin_bul

@admin_bul.route('/index')
def index():
    return render_template('admin/index.html')


@admin_bul.route('/login',methods=['GET','POST'])
def admin_login():

    if request.method == 'GET':
        return render_template('admin/login.html')

    # 登陆管理员
    name = request.form.get('username')
    password = request.form.get('password')
    if not all([name,password]):
        return render_template('admin/login.html',errmsg='密码或账号错误')

    # 查询数据库
    try:
        user = User.query.filter(User.mobile==name,User.is_admin==True).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据库错误')

    # 判断账号密码是否正确
    if (not user) or (not user.check_passowrd(password)):
        return render_template('admin/login.html',errmsg='账号或密码错误')

    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True

    return redirect(url_for('admin.index'))
